package com.zyk.scaffold.tcp.server.channel;

import com.zyk.scaffold.tcp.connector.TcpConnectionManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class ServerIdleStateTrigger extends ChannelInboundHandlerAdapter {

    private TcpConnectionManager tcpConnectionManager;

    public ServerIdleStateTrigger(TcpConnectionManager tcpConnectionManager) {
        tcpConnectionManager = tcpConnectionManager;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                log.warn("channel [{}] read out of heart time",ctx.channel().remoteAddress().toString());
                AttributeKey<String> sessionIdAttributeKey = AttributeKey.valueOf("SessionId");
                if(ctx.hasAttr(sessionIdAttributeKey)){
                    Attribute<String> sessionIdAttribute = ctx.attr(sessionIdAttributeKey);
                    String sessionId = sessionIdAttribute.get();
                    if(sessionId != null){
                        tcpConnectionManager.close(sessionId);
                    }
                }
                ctx.disconnect();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }


}